package com.bms.zuul.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author thinknovo
 * @version 1.0
 * @description RolesAuthorizationFilter.java
 * @date 2021/3/4 0:45
 */
public class MyRolesAuthorizationFilter extends RolesAuthorizationFilter {
    @Override
    public boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        System.out.println("----MyRolesAuthorizationFilter-------onAccessDenied-------------");
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setStatus(200);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        ObjectMapper json = new ObjectMapper();
        Map<String, Object> map = new HashMap<>();
        map.put("code",10500);
        map.put("msg","您没有该权限，请联系管理员授权！");
        System.out.println(map);
        out.print(json.writeValueAsString(map));
        out.flush();
        out.close();
        return false;
    }
    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {

        Subject subject = getSubject(request, response);
        String[] rolesArray = (String[]) mappedValue;
        //没有角色限制，有权限访问
        if (rolesArray == null || rolesArray.length == 0) {
            return true;
        }
        for (String s : rolesArray) {
            //若当前用户是rolesArray中的任何一个，则有权限访问
            if (subject.hasRole(s)) {
                return true;
            }
        }
        return false;
    }
}
